<template>
  <div class="search">
    <van-search
      v-model="inputValue"
      background="#d0584d"
      placeholder="请输入搜索关键词"
      show-action
      @input="search"
      @search="onSearch"
    >
      <template #action>
        <div class="right" @click="clear">
          取消
        </div>
      </template>
    </van-search>

    <div class="content" v-if="inputValue === ''">
      <div class="top">
        <van-cell title="单元格">
          <template #title>
            <div class="title">
              搜索历史
            </div>
          </template>
          <template #right-icon>
            <div class="right-icon" @click="delAllHistory">
              <van-icon name="delete" />
            </div>
          </template>
        </van-cell>
      </div>

      <div
        class="content-item"
        v-for="(item, index) in historyList"
        :key="index"
      >
        <searchCell
          icon="search"
          :title="item"
          right="cross"
          @delClick="del(index)"
          @goSearch="hoistClick(item)"
        ></searchCell>
      </div>
    </div>
    <div class="content" v-else>
      <div class="top">
        <van-cell title="单元格">
          <template #title>
            <div class="title">
              联想区域
            </div>
          </template>
        </van-cell>
      </div>

      <div
        class="content-item"
        v-for="(item, index) in lenovoList"
        :key="index"
      >
        <searchCell
          icon="search"
          :title="item.newItme"
          @delClick="del(index)"
          @goSearch="hoistClick(item)"
        ></searchCell>
      </div>
    </div>
  </div>
</template>

<script>
import searchCell from './searchCell'
import { localSet, localGet, localDel } from '@/utils/mylocal.js'
import { apiThink } from '@/api/other.js'
export default {
  name: 'search',
  data () {
    return {
      inputValue: '', // 搜索内容
      //  historyList: JSON.parse(localGet('history')) || [], // 搜索历史列表
      lenovoList: [], // 搜索联想列表
      historyList: []
    }
  },
  components: {
    searchCell
  },
  methods: {
    // 搜索 匹配大小写方法
    heightLight (string, keyword) {
      var reg = new RegExp(keyword, 'gi')
      string = string.replace(reg, function (txt) {
        return '<i style="color:red">' + txt + '</i>'
      })
      return string
    },
    // 联想补全
    async search () {
      // 非空字符不加入,已有的也不加入
      if (this.inputValue.trim() !== '') {
        this.lenovoList = []
        // 接口调用
        const res = await apiThink(this.inputValue)

        res.data.data.options.forEach(item => {
          // 将每条数据以输入的文本作分割成数组
          // console.log(item)
          const _txt = item.split(this.inputValue)

          // 进行文本替换转换成相应字符串
          const lenovo = _txt.join(
            `<span style="color:red">${this.inputValue}</span>`
          )
          //  console.log(this.heightLight(lenovo, this.inputValue))
          this.lenovoList.push({
            newItme: this.heightLight(lenovo, this.inputValue),
            item: item
          })
        })
      }
    },

    // 取消
    clear () {
      this.inputValue = ''
      if (this.$route.query.next) {
        this.$router.push(this.$route.query.next)
      }
    },
    // 清空所有历史
    delAllHistory () {
      this.$dialog
        .confirm({
          title: '温馨提示',
          message: '确认要删除所有历史吗'
        })
        .then(() => {
          // on confirm
          //  console.log('111')
          this.historyList = []
          localDel('history')
        })
        .catch(() => {
          // on cancel
        })
    },
    // 删除当前历史搜索记录
    del (index) {
      this.historyList.splice(index, 1)

      localSet('history', JSON.stringify(this.historyList))
    },
    // 关键词搜索
    hoistClick (item) {
      // console.log(item)
      if (item.item) {
        this.inputValue = item.item
        if (this.inputValue.trim() !== '') {
          // 数组循环
          // 每次添加为第一个
          this.historyList.unshift(this.inputValue)
          // set去重:它不能包含重复的项
          this.historyList = [...new Set(this.historyList)]
          // 只保存前3条记录
          this.historyList.splice(5)

          // 保留在本地
          localSet('history', JSON.stringify(this.historyList))
        }
        this.$router.push('/searchResult/' + item.item)
      } else {
        const _item = this.historyList.indexOf(item)
        //  如果当前点击为历史搜索
        if (_item !== -1) {
          // 把点击项更新为第一个
          // 每次添加为第一个
          this.historyList.unshift(this.historyList[_item])
          // set去重:它不能包含重复的项
          this.historyList = [...new Set(this.historyList)]
          // 只保存前3条记录
          this.historyList.splice(5)

          // 保留在本地

          localSet('history', JSON.stringify(this.historyList))
        }
        this.inputValue = item
        this.$router.push('/searchResult/' + item)
      }
    },
    onSearch (val) {
      this.hoistClick(val)
      if (this.inputValue.trim() !== '') {
        // 数组循环
        // 每次添加为第一个
        this.historyList.unshift(this.inputValue)
        // set去重:它不能包含重复的项
        this.historyList = [...new Set(this.historyList)]
        // 只保存前3条记录
        this.historyList.splice(5)

        // 保留在本地
        localSet('history', JSON.stringify(this.historyList))
      }
    }
  },
  created () {
    if (JSON.parse(localGet('history')) instanceof Array) {
      this.historyList = JSON.parse(localGet('history'))
    } else {
      localDel('history')
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  .van-search {
    .van-search__content {
      border-radius: 15px;
      height: 30px;
    }
    .van-search__action {
      background-color: #d0584d;
    }
    .right {
      color: #fff;
    }
  }

  .content {
    padding: 0 15px;
    .van-cell {
      padding-right: 0;
      padding-left: 0;
    }
    .van-icon {
      color: #000;
      font-size: 20px;
      line-height: 30px;
    }

    .content-item {
      border-bottom: 1px solid #f6f7f7;
    }
  }
}
</style>
